package com.ferryc.modules.sys.service.impl;

import java.util.List;

import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ferryc.commons.service.CommonService;
import com.ferryc.commons.utils.DigestUtil;
import com.ferryc.commons.utils.StringUtil;
import com.ferryc.constant.GlobalConstant;
import com.ferryc.modules.sys.entity.SysUser;
import com.ferryc.modules.sys.mapper.ISysUserMapper;
import com.ferryc.modules.sys.service.ISysUserService;

/**
 * 
 * 类名: ISysUsersService <br/>
 * 作用： 服务<br/>
 * 方法： <br/>
 * 创建者: Ferry C <br/>
 * 添加时间: 2017年12月04日 10:14:23 <br/>
 * 
 */
@Service
@Transactional(readOnly = true)
public class SysUsersServiceImpl extends CommonService<SysUser> implements ISysUserService {

	@Autowired
	private ISysUserMapper sysUsersMapper;

	@Override
	protected void init() {
		super.mapper = sysUsersMapper;
	}

	@Override
	@Transactional(readOnly = false)
	public void insertSysUser(SysUser sysUsers) {
		java.util.Random r = new java.util.Random();
		int num = r.nextInt();
		sysUsers.setSalt(DigestUtil.md5Hex(String.valueOf(num)));
		sysUsers.setPassword(DigestUtil.hashByShiro(GlobalConstant.MD5, sysUsers.getPassword().toCharArray(), ByteSource.Util.bytes(sysUsers.getSalt()), 1));
		sysUsersMapper.insert(sysUsers);
		sysUsersMapper.insertUserRole(sysUsers);
	}

	@Override
	@Transactional(readOnly = false)
	public void updateSysUser(SysUser sysUsers) {
		sysUsersMapper.deleteUserRole(sysUsers.getId());
		sysUsersMapper.update(sysUsers);
		sysUsersMapper.insertUserRole(sysUsers);
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteSysUser(SysUser sysUsers) {
		sysUsersMapper.deleteUserRole(sysUsers.getId());
		sysUsersMapper.update(sysUsers);
	}

	@Override
	public boolean cheakUserLoginName(SysUser sysUsers) {
		SysUser queryUser = new SysUser();
		queryUser.setStatus(StringUtil.EMPTY);
		queryUser.setDelFlag(GlobalConstant.DEL_FLAG_NORMAL);
		queryUser.setLoginName(sysUsers.getLoginName());
		List<SysUser> list = sysUsersMapper.listByEntity(queryUser);
		if (CollectionUtils.isEmpty(list)) {
			return Boolean.TRUE;
		}
		if (StringUtil.isBlank(sysUsers.getId())) {
			return Boolean.FALSE;
		} else {
			if (list.size() == 1 && list.get(0).getId().equals(sysUsers.getId())) {
				return Boolean.TRUE;
			}
			return Boolean.FALSE;
		}
	}

	@Override
	public List<String> getRoleByUserId(String userId) {
		return sysUsersMapper.getRoleByUserId(userId);
	}

	@Override
	public List<String> getPermByUserId(String userId) {
		return sysUsersMapper.getPermByUserId(userId);
	}

}